package com.yuanluludev.lib_base.base

import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.yuanluludev.lib_utils.util.LogUtils
import java.lang.Exception

/**
 * yuanLuLu
 * 带网络请求的基类并且带有viewDataBinding
 */
abstract class BaseVmWithDBActivity<VM : BaseViewModel, DB : ViewDataBinding> : BaseActivity() {

    protected open lateinit var mViewModel: VM
    protected open lateinit var mViewBinding: DB

    //Application全局的ViewModel
//    val appViewModel: BaseViewModel by lazy { getAppViewModel<BaseViewModel>()}

    override fun onCreate(savedInstanceState: Bundle?) {
        useDataBinding(true)
        super.onCreate(savedInstanceState)

        commonObserve()
        observe()

    }

    override fun initViewModel() {
        mViewModel = ViewModelProvider(this).get(viewModelClass())
    }

    override fun initDataBinding() {
        mViewBinding = DataBindingUtil.setContentView(this, getLayoutResId())
        mViewBinding.lifecycleOwner = this
    }

    /**
     * 获取ViewModel的class
     */
    protected abstract fun viewModelClass(): Class<VM>

    private fun commonObserve() {
        mViewModel.showLoadingWithTip.observe(this@BaseVmWithDBActivity) {
            showLoading(it)
        }
        mViewModel.showLoading.observe(this@BaseVmWithDBActivity) {
            if (it) showLoading()
        }
        mViewModel.hideLoading.observe(this@BaseVmWithDBActivity) {
            if (it) hideLoading()
        }
        mViewModel.successResultTip.observe(this@BaseVmWithDBActivity) {
            onSuccess(it.state, it.tipMessage)
        }
        mViewModel.errorResultTip.observe(this@BaseVmWithDBActivity) {
            onError(it.state, it.tipMessage)
        }
    }

    /**
     * 监听初始化相关
     */
    open fun observe() {
        // Override if need
    }

    /**
     * 请求成功
     */
    open fun onSuccess(successState: Int, successMsg: String) {
        // Override if need
    }

    /**
     * 请求失败
     */
    open fun onError(errorState: Int, errorMsg: String) {
        // Override if need
    }

}
